package com.cjq.es.service.impl;

import com.cjq.common.domain.request.ProjectQueryReq;
import com.cjq.common.domain.response.ProjectQueryRes;
import com.cjq.common.result.PageResult;
import com.cjq.common.result.Result;
import com.cjq.common.utils.StringUtils;
import com.cjq.es.service.EsService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class EsServiceImpl implements EsService {
    private final static String INDEX_NAME="project";

    @Override
    public Result<PageResult<ProjectQueryRes>> search(ProjectQueryReq projectQueryReq) {
        /**
         * 返回结果集
         */
        long total = 0;
        ArrayList<ProjectQueryRes> projectQueryRes = new ArrayList<>();


        //创建 条件查询请求对象
        SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
        //创建 条件查询构造器
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //创建 多条件拼接对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //开始 条件拼接
        if (StringUtils.isNotBlank(projectQueryReq.getCustomer())){
            boolQueryBuilder.must(QueryBuilders.matchQuery("customer",projectQueryReq.getCustomer()));
        }


        //把 多条件拼接对象 给 条件查询构造器
        SearchSourceBuilder query = searchSourceBuilder.query(boolQueryBuilder);

        //分页
        if (projectQueryReq.getPageNum()!=null){
            query.from(projectQueryReq.getPageNum());
        }
        if (projectQueryReq.getPageSize()!=null){
            query.size((projectQueryReq.getPageNum()-1)*projectQueryReq.getPageSize());
        }





        return PageResult.toResult(total,projectQueryRes);
    }
}
